package com.android.nfctouch.ui.activity;

import android.Manifest;
import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Handler;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.fragment.app.FragmentActivity;

import com.android.baselibrary.dialog.CommList_DialogFragment;
import com.android.baselibrary.interface_.CommCallBack;
import com.android.baselibrary.interface_.OkHttpCallBack;
import com.android.baselibrary.responce.BaseResponce;
import com.android.baselibrary.tool.AndPermisionUtil;
import com.android.baselibrary.tool.CommLoading;
import com.android.baselibrary.tool.CommToast;
import com.android.baselibrary.tool.Log;
import com.android.baselibrary.util.GlideEngine;
import com.android.baselibrary.util.GlideUtil;
import com.android.baselibrary.view.Comm_HeadView;
import com.android.baselibrary.view.MultiStateView;
import com.android.nfctouch.R;
import com.android.nfctouch.bean.UpLoadedFileInfo;
import com.android.nfctouch.bean.UserInfo;
import com.android.nfctouch.constants.Constants;
import com.android.nfctouch.manager.API_Manager;
import com.android.nfctouch.manager.SysConfigHelper;
import com.android.nfctouch.manager.UserManager;
import com.android.nfctouch.ui.view.EditUserInfoView;
import com.github.gzuliyujiang.wheelpicker.DatePicker;
import com.github.gzuliyujiang.wheelpicker.OptionPicker;
import com.github.gzuliyujiang.wheelpicker.annotation.DateMode;
import com.github.gzuliyujiang.wheelpicker.contract.OnDatePickedListener;
import com.github.gzuliyujiang.wheelpicker.contract.OnOptionPickedListener;
import com.github.gzuliyujiang.wheelpicker.entity.DateEntity;
import com.github.gzuliyujiang.wheelpicker.widget.DateWheelLayout;
import com.hjq.permissions.OnPermissionCallback;
import com.hjq.permissions.XXPermissions;
import com.luck.picture.lib.basic.PictureSelector;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.config.SelectMimeType;
import com.luck.picture.lib.entity.LocalMedia;
import com.luck.picture.lib.interfaces.OnResultCallbackListener;
import com.yanzhenjie.permission.runtime.Permission;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

public class EditUserInfoActivity extends BaseActivity {

    @BindView(R.id.multiplestatusView)
    MultiStateView multiplestatusView;
    @BindView(R.id.comm_title)
    Comm_HeadView comm_title;
    @BindView(R.id.iv_head)
    ImageView iv_head;
    @BindView(R.id.iv_bg)
    ImageView iv_bg;
    @BindView(R.id.info_birthday)
    EditUserInfoView info_birthday;
    @BindView(R.id.info_remark)
    EditUserInfoView info_remark;
    @BindView(R.id.info_sex)
    EditUserInfoView info_sex;
    @BindView(R.id.info_nickname)
    EditUserInfoView info_nickname;
    @BindView(R.id.info_phone)
    EditUserInfoView info_phone;

    UserInfo userInfo;
    Handler handler = new Handler();

    @Override
    protected int getLayoutId() {
        return R.layout.activity_edit_userinfo;
    }

    @Override
    protected void initView() {
        comm_title.setTitle("编辑资料");
    }

    @Override
    protected void initData() {
        getUserInfo();
    }

    //获取用户信息
    private void getUserInfo() {
        API_Manager.userInfo(mContext, new OkHttpCallBack<BaseResponce<UserInfo>>() {
            @Override
            public void onSuccess(BaseResponce<UserInfo> baseResponce) {
                userInfo = baseResponce.getData();
                bindUserInfo();
            }

            @Override
            public void onFailure(BaseResponce<UserInfo> baseResponce) {

            }
        });
    }

    private void bindUserInfo() {
        GlideUtil.displayImage(mContext, userInfo.avatarUrl, iv_head, -1);
        GlideUtil.displayImage(mContext, userInfo.backgroundUrl, iv_bg, -1);
        info_remark.setContent(userInfo.remark);
        info_sex.setContent(userInfo.sex);
        info_nickname.setContent(userInfo.username);
        info_birthday.setContent(userInfo.birthday);
        info_phone.setContent(userInfo.phone);

    }

    @OnClick({R.id.iv_head, R.id.iv_bg, R.id.info_sex, R.id.info_nickname, R.id.info_remark, R.id.info_birthday})
    public void onViewClicked(View view) {
        Intent intent;
        switch (view.getId()) {
            case R.id.iv_head:   //头像
                getHeadPic();
                break;
            case R.id.iv_bg:   //背景
                String defaultBg = SysConfigHelper.getConfig(SysConfigHelper.Config_Background);
                if (userInfo.backgroundUrl.equals(defaultBg)) {
                    //没设置背景,直接传图片
                    getBgPic();
                } else {
                    //有背景了，
                    List<String> list = new ArrayList<>();
                    list.add("更换背景图");
                    list.add("重置默认背景");
                    CommList_DialogFragment.showCommDialog((FragmentActivity) mContext, list, true, new CommCallBack() {
                        @Override
                        public void onResult(Object obj) {
                            int index = (int) obj;
                            if (index == 0) {
                                getBgPic();
                            } else if (index == 1) {
                                saveUserInfo("backgroundUrl", "");
                            }
                        }
                    }, null);
                }
                break;
            case R.id.info_sex:
                List<String> data = new ArrayList<>();
                data.add("男");
                data.add("女");
                data.add("保密");
                OptionPicker picker = new OptionPicker(this);
                picker.setTitle("");
                picker.setBodyWidth(140);
                picker.setData(data);
                picker.setDefaultPosition(data.indexOf(userInfo.sex));
                picker.setOnOptionPickedListener(new OnOptionPickedListener() {
                    @Override
                    public void onOptionPicked(int position, Object item) {
                        saveUserInfo("sex", item.toString());
                    }
                });
                picker.show();
                break;
            case R.id.info_nickname:   //设置昵称
                intent = new Intent(mContext, CommInputActivity.class);
                intent.putExtra("title", "修改昵称");
                intent.putExtra("tips", "请输入昵称，最多20个字符");
                intent.putExtra("hint", "请输入昵称");
                intent.putExtra("length", 20);
                startActivityForResult(intent, 100);
                break;
            case R.id.info_remark:
                intent = new Intent(mContext, CommInputActivity.class);
                intent.putExtra("title", "修改简介");
                intent.putExtra("tips", "请输入简介，最多50个字符");
                intent.putExtra("hint", "请输入简介");
                intent.putExtra("length", 50);
                intent.putExtra("isMultipleLine", true);
                startActivityForResult(intent, 101);
                break;
            case R.id.info_birthday:
                DatePicker datePicker = new DatePicker(this);
                //picker.setBodyWidth(240);
                DateWheelLayout wheelLayout = datePicker.getWheelLayout();
                wheelLayout.setDateMode(DateMode.YEAR_MONTH_DAY);
                //wheelLayout.setDateLabel("年", "月", "日");
                //wheelLayout.setDateFormatter(new UnitDateFormatter());
                wheelLayout.setRange(DateEntity.yearOnFuture(-60), DateEntity.today(), DateEntity.today());
//                wheelLayout.setCurtainEnabled(true);
                //wheelLayout.setCurtainColor(0xFFCC0000);
                //wheelLayout.setIndicatorEnabled(true);
                //wheelLayout.setIndicatorColor(0xFFFF0000);
                //wheelLayout.setIndicatorSize(view.getResources().getDisplayMetrics().density * 2);
                //wheelLayout.setTextColor(0xCCCC0000);
                //wheelLayout.setSelectedTextColor(0xFFFF0000);
                //wheelLayout.getYearLabelView().setTextColor(0xFF999999);
                //wheelLayout.getMonthLabelView().setTextColor(0xFF999999);
                wheelLayout.getYearLabelView().setTextSize(10);
                datePicker.getWheelLayout().setResetWhenLinkage(false);
                datePicker.setOnDatePickedListener(new OnDatePickedListener() {
                    @Override
                    public void onDatePicked(int year, int month, int day) {
                        String str = String.format("%02d-%02d-%02d", year, month, day);
                        saveUserInfo("birthday", str);
                    }
                });
                datePicker.show();
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (data == null) return;
        String text = data.getStringExtra("text");
        switch (requestCode) {
            case 100:  //昵称
                saveUserInfo("username", text);
                break;
            case 101:  //简介
                saveUserInfo("remark", text);
                break;

        }
    }

    //修改头像
    private void getHeadPic() {
        String[] permissions = new String[]{android.Manifest.permission.WRITE_EXTERNAL_STORAGE, android.Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.CAMERA};
        //是否永久拒绝了权限
        boolean isPermanentDenied = XXPermissions.isPermanentDenied((Activity) mContext, permissions);
        XXPermissions.with(mContext).permission(permissions).request(new OnPermissionCallback() {
            @Override
            public void onGranted(List<String> permissions, boolean all) {
                //权限允许
                PictureSelector.create(mContext)
                        .openGallery(SelectMimeType.ofImage())
                        .setImageEngine(GlideEngine.createGlideEngine())
                        .setMaxSelectNum(1)  //一次最多选几张图
                        .forResult(new OnResultCallbackListener<LocalMedia>() {
                            @Override
                            public void onResult(ArrayList<LocalMedia> result1) {
                                LocalMedia media = result1.get(0);
                                Log.i("media.getPath():" + media.getRealPath());
                                common_upload(new File(media.getRealPath()), 1);
                            }

                            @Override
                            public void onCancel() {
                            }
                        });
            }

            @Override
            public void onDenied(List<String> permissions, boolean never) {
                //权限被拒绝
                if (never) {
                    if (isPermanentDenied)  //永久拒绝了，只能跳系统设置页打开
                    {
                        XXPermissions.startPermissionActivity(mContext, permissions);
                        Toast.makeText(mContext, "您已经拒绝了相册权限，需要在系统设置中将权限打开后重试", Toast.LENGTH_LONG).show();
                    }
                } else {
                    Toast.makeText(mContext, "您拒绝了相册权限，无法使用相册功能", Toast.LENGTH_LONG).show();
                }
            }
        });
    }

    //修改背景
    private void getBgPic() {
        String[] permissions = new String[]{android.Manifest.permission.WRITE_EXTERNAL_STORAGE, android.Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.CAMERA};
        //是否永久拒绝了权限
        boolean isPermanentDenied = XXPermissions.isPermanentDenied((Activity) mContext, permissions);
        XXPermissions.with(mContext).permission(permissions).request(new OnPermissionCallback() {
            @Override
            public void onGranted(List<String> permissions, boolean all) {
                //权限允许
                PictureSelector.create(mContext)
                        .openGallery(SelectMimeType.ofImage())
                        .setImageEngine(GlideEngine.createGlideEngine())
                        .setMaxSelectNum(1)  //一次最多选几张图
                        .forResult(new OnResultCallbackListener<LocalMedia>() {
                            @Override
                            public void onResult(ArrayList<LocalMedia> result1) {
                                LocalMedia media = result1.get(0);
                                Log.i("media.getPath():" + media.getRealPath());
                                common_upload(new File(media.getRealPath()), 2);
                            }

                            @Override
                            public void onCancel() {
                            }
                        });
            }

            @Override
            public void onDenied(List<String> permissions, boolean never) {
                //权限被拒绝
                if (never) {
                    if (isPermanentDenied)  //永久拒绝了，只能跳系统设置页打开
                    {
                        XXPermissions.startPermissionActivity(mContext, permissions);
                        Toast.makeText(mContext, "您已经拒绝了相册权限，需要在系统设置中将权限打开后重试", Toast.LENGTH_LONG).show();
                    }
                } else {
                    Toast.makeText(mContext, "您拒绝了相册权限，无法使用相册功能", Toast.LENGTH_LONG).show();
                }
            }
        });
    }

    //上传文件  type: 1-头像，2-背景，3-通用
    private void common_upload(File file, int type) {
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                CommLoading.showLoading((FragmentActivity) mContext);
            }
        }, 200);
        API_Manager.common_upload(mContext, file, type, new OkHttpCallBack<BaseResponce<UpLoadedFileInfo>>() {
            @Override
            public void onSuccess(BaseResponce<UpLoadedFileInfo> baseResponce) {
                Log.i("path:" + baseResponce.data.path);
                UpLoadedFileInfo fileInfo = baseResponce.data;
                if (type == 1) {
                    saveUserInfo("avatarUrl", fileInfo.path);
                } else if (type == 2) {
                    saveUserInfo("backgroundUrl", fileInfo.path);
                }
            }

            @Override
            public void onFailure(BaseResponce<UpLoadedFileInfo> baseResponce) {
                CommLoading.dismissLoading();
                CommToast.showToast(mContext, Constants.NetError);
            }
        });
    }

    //保存用户信息
    private void saveUserInfo(String key, String value) {
        API_Manager.user_update(mContext, key, value, new OkHttpCallBack<BaseResponce<String>>() {
            @Override
            public void onSuccess(BaseResponce<String> baseResponce) {
                CommLoading.dismissLoading();
                getUserInfo();
                CommToast.showToast(mContext, "已保存");
//                CommToast.showToast(mContext, baseResponce.getMessage());
            }

            @Override
            public void onFailure(BaseResponce<String> baseResponce) {
                CommLoading.dismissLoading();
                CommToast.showToast(mContext, baseResponce.msg);
            }
        });

    }
}
